package com.expdatacloud.service.impl;

import com.expdatacloud.entity.*;
import com.expdatacloud.mapper.*;
import com.expdatacloud.service.IqcCheckItemDetailsService;
import com.expdatacloud.service.IqcDetectionService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 检验明细表 服务实现类
 * </p>
 *
 * @author jie
 * @since 2019-11-14
 */
@Service
@Transactional
public class IqcCheckItemDetailsServiceImpl implements IqcCheckItemDetailsService {

    @Autowired
    private IqcDetectionService iqcDetectionService;
    @Autowired
    private InspectionItemsListMapper inspectionItemsListMapper;
    @Autowired
    private InspectionItemsListDetailMapper inspectionItemsListDetailMapper;
    @Autowired
    private IqcCheckItemDetailsMapper mapper;
    @Autowired
    private IqcDetectionHistoryMapper iqcDetectionHistoryMapper;
    @Autowired
    private IqcCheckItemDetailsHistoryMapper iqcCheckItemDetailsHistoryMapper;
    @Autowired
    private IqcDetectionDetailHistoryMapper iqcDetectionDetailHistoryMapper;
    @Autowired
    private ItrnMapper itrnMapper;


    @Override
    public List<IqcCheckItemDetails> list(String checkProjectKey, String receiptKey, String sku) {
        return mapper.list(checkProjectKey, receiptKey, sku);
    }

    @Override
    public int update(IqcCheckItemDetails iqcCheckItemDetails) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        iqcCheckItemDetails.setEditDate(dateFormat.format(new Date()));
        return mapper.update(iqcCheckItemDetails);
    }

    @Override
    public int insert(IqcCheckItemDetails iqcCheckItemDetails) {
        return mapper.insert(iqcCheckItemDetails);
    }


    @Override
    public void writeData(List<IqcCheckItemDetails> iqcCheckItemDetailsList, String checkItemName,
                          String receiptKey, String sku, String user) {
        if (iqcCheckItemDetailsList.size() > 0 && iqcCheckItemDetailsList.get(0).getCheckItemName() != null) {
            if (!iqcCheckItemDetailsList.get(0).getCheckItemName().equals(checkItemName)) {
                mapper.delete(receiptKey, sku);
                insertCheckItem(checkItemName, receiptKey, sku, user);
            }
        } else {
            insertCheckItem(checkItemName, receiptKey, sku, user);
        }
    }

    private void insertCheckItem(String checkItemName, String receiptKey, String sku, String user) {
        //获取检验项详情
        IqcDetection iqcDetectionParm = new IqcDetection();
        iqcDetectionParm.setSku(sku);
        iqcDetectionParm.setReceiptKey(receiptKey);
        IqcDetection iqcDetection = iqcDetectionService.getByReceiptkeyAndSku(iqcDetectionParm);
        //获取检验项目集合，通过检验项目集合 checkprojectkey 查询 详情表 根据检验项目名称查询
        InspectionItemsList inspectionItemsList = new InspectionItemsList();
        inspectionItemsList.setCheckProjectName(checkItemName);
        InspectionItemsList inspectionItemsList2 = inspectionItemsListMapper.list(inspectionItemsList);
        //查询详情表
        if (null != inspectionItemsList2) {
            InspectionItemsListDetail inspectionItemsListDetail = new InspectionItemsListDetail();
            inspectionItemsListDetail.setCheckProListKey(inspectionItemsList2.getCheckProjectKey());
            List<InspectionItemsListDetail> inspectionItemsListDetailList = inspectionItemsListDetailMapper.list(inspectionItemsListDetail);

            //插入到 IqcCheckItemDetails
            if (inspectionItemsListDetailList.size() != 0) {
                for (InspectionItemsListDetail itemsListDetail : inspectionItemsListDetailList) {
                    IqcCheckItemDetails iqcCheckItemDetails = new IqcCheckItemDetails();
                    iqcCheckItemDetails.setReceiptKey(receiptKey);
                    iqcCheckItemDetails.setSku(iqcDetection.getSku());
                    iqcCheckItemDetails.setAddWho(user);
                    iqcCheckItemDetails.setCheckItemName(inspectionItemsList2.getCheckProjectName());
                    iqcCheckItemDetails.setCheckProject(itemsListDetail.getCheckProject());
                    iqcCheckItemDetails.setCheckStandard(itemsListDetail.getCheckStandard());
                    iqcCheckItemDetails.setCheckType(itemsListDetail.getCheckType());
                    iqcCheckItemDetails.setCheckCategory(itemsListDetail.getCheckCategory());
                    iqcCheckItemDetails.setCriticalDefect(itemsListDetail.getFatal_Defect() == null ? "" : itemsListDetail.getFatal_Defect());
                    iqcCheckItemDetails.setSeriousDefects(itemsListDetail.getSerious_Defect() == null ? "" : itemsListDetail.getSerious_Defect());
                    iqcCheckItemDetails.setLightDefects(itemsListDetail.getMinor_Defects() == null ? "" : itemsListDetail.getMinor_Defects());
                    iqcCheckItemDetails.setRemark(itemsListDetail.getBad_Describe() == null ? "" : itemsListDetail.getBad_Describe());
                    iqcCheckItemDetails.setDescribe(inspectionItemsList2.getDescr());
                    iqcCheckItemDetails.setNumberOfDefectiveSa(itemsListDetail.getNumberOfDefectives());
                    mapper.insert(iqcCheckItemDetails);
                }
            }
        }
    }

    @Override
    public String pro_yt_3nod_move(List<IqcDetectionDetail> iqcDetectionDetailList, String user,
                                   IqcDetection iqcDetection) {
         /*  p_storerkey  nvarchar2,           --货主
        p_sku        nvarchar2,           --货品
        p_lot        nvarchar2,           --批次号
        p_fromloc    nvarchar2,           --自库位
        p_toloc      nvarchar2,           --至库位
        p_id         nvarchar2,           --自箱号
        p_toid       in out nvarchar2,    --至箱号
        p_qty        number,              --移动数量
        p_who        NVARCHAR2,           --操作人

        o_rs         OUT NVARCHAR2,       --返回消息 S成功 非S失败
        o_msg        OUT NVARCHAR2        --返回消息*/
        //移库
        if (iqcDetectionDetailList.size() != 0) {
            for (IqcDetectionDetail detectionDetail : iqcDetectionDetailList) {
                if (detectionDetail.getCheckBackQuantity() > 0 || detectionDetail.getInventoryQuantity() > 0) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("p_storerkey", detectionDetail.getShipper());
                    map.put("p_sku", detectionDetail.getSku());
                    map.put("p_lot", detectionDetail.getLot());
                    map.put("p_fromloc", detectionDetail.getLoc());
                    map.put("p_id", StringUtils.isEmpty(detectionDetail.getID()) ? " " : detectionDetail.getID());
                    map.put("p_toid", " ");
                    map.put("p_who", user);


                    //内部转移存储
                    String toLoc = mapper.getToLoc(detectionDetail.getShipper());
                    HashMap<String, Object> map2 = new HashMap<>();
                    map2.put("p_storerkey", detectionDetail.getShipper());
                    map2.put("p_sku", detectionDetail.getSku());
                    map2.put("p_lot", detectionDetail.getLot());
                    map2.put("p_fromloc", toLoc);
                    map2.put("p_id", StringUtils.isEmpty(detectionDetail.getID()) ? " " : detectionDetail.getID());
                    map2.put("p_toid", " ");
                    map2.put("p_who", user);

                    // 扣除留样库存存储
                    Map<String, Object> itrnMap = new HashMap<>();


                    if (detectionDetail.getRejectionQuantity() > 0) {
                        //移库存储
                        map.put("p_toloc", toLoc);
                        map.put("p_qty", detectionDetail.getRejectionQuantity());
                        map.put("p_receiptkey", iqcDetection.getReceiptKey());
                        mapper.pro_yt_3nod_iqcmove(map);

                        //内部转移
                        map2.put("p_toloc", toLoc);
                        map2.put("p_qty", detectionDetail.getRejectionQuantity());
                        map2.put("p_receiptkey", iqcDetection.getReceiptKey());

                        mapper.pro_yt_3nod_IqcTransfer(map2);
                    }
                    if (detectionDetail.getInventoryQuantity() > 0) {
                        map.put("p_toloc", "STAGE-OK");
                        map.put("p_qty", detectionDetail.getInventoryQuantity());
                        map.put("p_receiptkey", iqcDetection.getReceiptKey());
                        mapper.pro_yt_3nod_iqcmove(map);
                    }

                    // 如果留样数量大于零则扣除留样数量
                    if (detectionDetail.getSampleQuantity() > 0) {
//                        Itrn itrn = new Itrn();
//                        itrn.setStorerkey(detectionDetail.getShipper());
//                        itrn.setSku(detectionDetail.getSku());
//                        itrn.setLot(detectionDetail.getLot());
//                        itrn.setLoc(detectionDetail.getLoc());
//                        itrn.setReceiptkey(detectionDetail.getReceiptKey());
//                        itrn.setUser(user);
//                        itrn.setQty("-"+detectionDetail.getSampleQuantity());


                        itrnMap.put("p_storerkey", detectionDetail.getShipper());
                        itrnMap.put("p_sku", detectionDetail.getSku());
                        itrnMap.put("p_loc", detectionDetail.getLoc());
                        itrnMap.put("p_lot", detectionDetail.getLot());
                        itrnMap.put("p_id", StringUtils.isEmpty(detectionDetail.getID()) ? " " : detectionDetail.getID());
                        itrnMap.put("p_qty", detectionDetail.getSampleQuantity());
                        itrnMap.put("p_sourceKey", detectionDetail.getReceiptKey());
                        itrnMap.put("p_who", user);

                        itrnMapper.pro_yt_3nod_deductliuyang(itrnMap);
                    }

                    if ("E".equals(map.get("o_rs"))) {
                        throw new RuntimeException("调用移库存储出错" + map.get("o_msg"));
                    }
                    if ("E".equals(map2.get("o_rs"))) {
                        throw new RuntimeException("调用内部转移存储出错" + map2.get("o_msg"));
                    }
                    if ("E".equals(itrnMap.get("o_rs"))) {
                        throw new RuntimeException("调用扣除留样库存存储出错" + itrnMap.get("o_msg"));
                    }
                }
            }
        }

        return "ok";
    }


    @Override
    public String getUDF1() {
        return mapper.getUDF1();
    }

    @Override
    public int writeDateToHistory(String users, String library, IqcDetection iqcDetection, List<IqcCheckItemDetails> iqcCheckItemDetails, List<IqcDetectionDetail> iqcDetectionDetail) {
        int result = 0;
        IqcDetectionHistory iqcDetectionHistory = new IqcDetectionHistory();
        BeanUtils.copyProperties(iqcDetection, iqcDetectionHistory);
        iqcDetectionHistory.setAddDate(new Date());
        iqcDetectionHistory.setAddWho(users);
        iqcDetectionHistory.setWhseId(library);
        String historyId = iqcDetectionDetailHistoryMapper.getHistoryId();
        iqcDetectionHistory.setHistoryId(historyId);
        iqcDetectionHistory.setInspectionCategory(iqcDetection.getInspectionCategory());

        String loc = mapper.getToLoc(iqcDetection.getShipper());

        if (iqcDetection.getRejectionQuantity() == 0d || (iqcDetection.getRejectionQuantity() != 0d && iqcDetection.getInventoryQuantity() != 0d)) {
            iqcDetectionHistory.setLoc("STAGE-OK");
        } else {
            iqcDetectionHistory.setLoc(loc);
        }

        if (CollectionUtils.isNotEmpty(iqcCheckItemDetails)) {
            iqcDetectionHistory.setCheckCategory(iqcCheckItemDetails.get(0).getCheckType());
        }

        iqcDetectionHistoryMapper.insert(iqcDetectionHistory);

        for (IqcCheckItemDetails iqcCheckItemDetail : iqcCheckItemDetails) {
            IqcCheckItemDetailsHistory iqcCheckItemDetailsHistory = new IqcCheckItemDetailsHistory();
            BeanUtils.copyProperties(iqcCheckItemDetail, iqcCheckItemDetailsHistory);
            iqcCheckItemDetailsHistory.setAddDate(new Date());
            iqcCheckItemDetailsHistory.setAddWho(users);
            iqcCheckItemDetailsHistory.setWhseId(library);
            iqcCheckItemDetailsHistory.setHistoryId(historyId);
            iqcCheckItemDetailsHistoryMapper.insert(iqcCheckItemDetailsHistory);
        }

        for (IqcDetectionDetail detectionDetail : iqcDetectionDetail) {
            IqcDetectionDetailHistory iqcDetectionDetailHistory = new IqcDetectionDetailHistory();
            BeanUtils.copyProperties(detectionDetail, iqcDetectionDetailHistory);

            if (detectionDetail.getRejectionQuantity() == 0d || (detectionDetail.getRejectionQuantity() != 0d && detectionDetail.getInventoryQuantity() != 0d)) {
                iqcDetectionHistory.setLoc("STAGE-OK");
            } else {
                iqcDetectionHistory.setLoc(loc);
            }
            iqcDetectionDetailHistory.setAddDate(new Date());
            iqcDetectionDetailHistory.setAddWho(users);
            iqcDetectionDetailHistory.setWhseId(library);
            iqcDetectionDetailHistory.setHistoryId(historyId);
            iqcDetectionDetailHistory.setReceiptLineNumber(detectionDetail.getReceiptLineNumber());
            iqcDetectionDetailHistory.setReceiptLineNumber(detectionDetail.getReceiptLineNumber());
            result = iqcDetectionDetailHistoryMapper.insert(iqcDetectionDetailHistory);
        }
        return result;
    }

    @Override
    public int insertToHistory(String users, String library, IqcDetection iqcDetection, List<IqcCheckItemDetails> iqcCheckItemDetails) {

        IqcDetectionHistory iqcDetectionHistory = iqcDetectionHistoryMapper.getBySkuAndExtreceiptform(iqcDetection.getSku(), iqcDetection.getExtReceiptForm());

        if (null == iqcDetectionHistory) {
            throw new RuntimeException("履历数据不存在");
        }

        for (IqcCheckItemDetails iqcCheckItemDetail : iqcCheckItemDetails) {
            IqcCheckItemDetailsHistory iqcCheckItemDetailsHistory = new IqcCheckItemDetailsHistory();
            BeanUtils.copyProperties(iqcCheckItemDetail, iqcCheckItemDetailsHistory);
            iqcCheckItemDetailsHistory.setAddDate(new Date());
            iqcCheckItemDetailsHistory.setAddWho(users);
            iqcCheckItemDetailsHistory.setWhseId(library);
            iqcCheckItemDetailsHistory.setHistoryId(iqcDetectionHistory.getHistoryId());
            iqcCheckItemDetailsHistoryMapper.insert(iqcCheckItemDetailsHistory);
        }


        return 0;
    }

    @Override
    public String sysToAddInspectionCategory(String receiptkey, String sku, String user) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("p_receiptkey", receiptkey);
        map.put("p_sku", sku);
        map.put("p_who", user);
        mapper.sysToAddInspectionCategory(map);
        if (!"S".equals(map.get("o_rs"))) {
            throw new RuntimeException("调用添加检验品类存储出错" + map.get("o_msg"));
        }
        return "ok";
    }


}
